package com.ys.controller.api.account;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.ys.util.CheckUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.config.MenuId;
import com.ys.entity.account.TcwNeedPayLedgerDetail;
import com.ys.entity.sys.YsCol;
import com.ys.enume.account.TcwNeedPayLedgerDetailEnum;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.account.TcwNeedPayLedgerDetailService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/api/inter/tcwNeedPayLedgerDetail")
public class ApiInterTcwNeedPayLedgerDetailController {
	private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwNeedPayLedgerDetailController.class);
	
	@Autowired
	private CommonApiService<TcwNeedPayLedgerDetail> commonApiService;
	@Autowired
	private TcwNeedPayLedgerDetailService tcwNeedPayLedgerDetailService;

	@Autowired
	private CheckUtil checkUtil;
	
	@RequiresPermissions("tcwNeedPayLedgerDetail:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcwNeedPayLedgerDetail cond){
		
		cond = setSeachSql(cond);
		
		cond.setOrderby("A.Id DESC");
		
		return commonApiService.searchLay(cond);
	}
	/**
	 * 新增
	 */
	@RequestMapping("/add")
	@ResponseBody
	@RequiresPermissions("tcwNeedPayLedgerDetail:add")
	public R add(String needPayAccountCode, String subData) {
		try {
			return tcwNeedPayLedgerDetailService.add(needPayAccountCode, subData);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 编辑
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:edit")
	@PostMapping("/edit")
    @ResponseBody
	public R edit(@RequestParam Map<String, Object> params){
		try {
			return tcwNeedPayLedgerDetailService.edit(params);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwNeedPayLedgerDetail cond) throws Exception{
		
		cond = setSeachSql(cond);
		
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCW_NeedPayLedgerDetail)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
        ExportExcelUtils<TcwNeedPayLedgerDetail> util = new ExportExcelUtils<TcwNeedPayLedgerDetail>(new TcwNeedPayLedgerDetail());
        
        String toFilePath = util.exportExcel(listData, listField, "应付台账明细");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcwNeedPayLedgerDetail setSeachSql(TcwNeedPayLedgerDetail cond){
    	
    	cond
    		.addField("(A.CostPrice + A.ServicePrice) * A.Quantity totalPrice")
    		.addField("(A.CostPrice * A.Quantity - A.PayedPrice) unpayPrice")
				.addField("(A.ProxyPrice) * A.Quantity proxyTotalPrice");
    	
    	cond.addLeftJoin("TCW_NeedPayAccount B ON B.Code = A.NeedPayAccountCode")
    		.addField("B.Name needPayAccountName");
    	
    	cond.addLeftJoin("THR_OperateCompanyApply B1 ON B1.Vgsbm = B.Vgsbm")
			.addField("B1.Vgsbm needPayAccountVgsbm")
    		.addField("B1.Vgsjc needPayAccountVgsjc");
    	
    	cond.addLeftJoin("TB_NeedPayType C ON C.Code = A.NeedPayTypeCode")
    		.addField("C.Name needPayTypeName");
		
		cond.addLeftJoin("TS_UserChange D ON D.Id = A.CreateChangeId")
		.addField("D.UserId createUserId")
		.addField("D.DeptName createOrgName");
		
		cond.addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = A.Vgsbm")
			.addField("E.Vgsjc vgsjc");
		
        return  cond;
    }

	/**
	 * 弹出框
	 */
	@RequestMapping("/searchForModal")
	@ResponseBody
	public LayuiTableVoJA searchForModal(@ModelAttribute TcwNeedPayLedgerDetail cond){
		cond
			.setState(TcwNeedPayLedgerDetailEnum.State.NOT_FINISH.value)
			.addField("(A.CostPrice * A.Quantity + A.ServicePrice) totalPrice")
			.addField("(A.CostPrice * A.Quantity - A.PayedPrice) unpayPrice")
			.addField("(A.ProxyPrice) * A.Quantity proxyTotalPrice");
    	
    	cond.addLeftJoin("TB_NeedPayType C ON C.Code = A.NeedPayTypeCode")
    		.addField("C.Name needPayTypeName");
		
		cond.addLeftJoin("THR_OperateCompanyApply E ON E.Vgsbm = A.Vgsbm")
			.addField("E.Vgsjc vgsjc");
		cond.setTransferStatus(1);//已划拨的才能调取
    	
		return commonApiService.searchLay(cond);
	}



	/**
	 * 划拨，生成流水
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:doTransferFlow")
	@RequestMapping("/doTransferFlow")
	@ResponseBody
	public R doTransferFlow(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			String resMsg = "";
			for (int i=0;i<idList.size();i++){
				R res = tcwNeedPayLedgerDetailService.doTransferFlow(Long.parseLong(idList.get(i)));
				if(res.getCode().equals( R.Code.FAILED.value)){
					resMsg += "划拨的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
				}

			}
			return R.ok(resMsg);
		} catch (IllegalArgumentException e) {
			return R.error(e.getMessage());
		} catch (Exception e) {
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}



	/**
	 * 复制
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:copy")
	@RequestMapping("/doCopy")
	@ResponseBody
	public R doCopy(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			for (int i=0;i<idList.size();i++){
				tcwNeedPayLedgerDetailService.doCopy(Long.parseLong(idList.get(i)));

			}
			return R.ok();
		} catch (IllegalArgumentException e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}




	/**
	 * 删除
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:del")
	@RequestMapping("/doDelByList")
	@ResponseBody
	public R doDelByList(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			String resMsg = "";
			int count = 0;
			for (int i=0;i<idList.size();i++){
				R res = tcwNeedPayLedgerDetailService.doDel(Long.parseLong(idList.get(i)));
				if(res.getCode().equals( R.Code.FAILED.value)){
					resMsg += "删除的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
				}else {
					count++;
				}

			}
			return R.ok("成功操作"+count+"条数据</br>"+resMsg);
		} catch (IllegalArgumentException e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}



	/**
	 * 批量设置成本价
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:setUnitPrice")
	@RequestMapping("/setUnitPrice")
	@ResponseBody
	public R setUnitPrice(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {

			if(checkUtil.isNullByObject(params.get("unitPrice"))){
				return R.error("请输入成本价");
			}
			if(!checkUtil.checkNumber( params.get("unitPrice").toString())){
				return R.error("成本价应为数字");
			}
			BigDecimal unitPrice = new BigDecimal(params.get("unitPrice").toString());
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			String resMsg = "";
			int count = 0;
			for (int i=0;i<idList.size();i++){
				R res = tcwNeedPayLedgerDetailService.setUnitPrice(Long.parseLong(idList.get(i)),unitPrice);
				if(res.getCode().equals( R.Code.FAILED.value)){
					resMsg += "批量设置的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
				}else {
					count++;
				}

			}
			return R.ok("成功操作"+count+"条数据</br>"+resMsg);
		} catch (IllegalArgumentException e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}



	/**
	 * 批量设置代理价
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:setProxyPrice")
	@RequestMapping("/setProxyPrice")
	@ResponseBody
	public R setProxyPrice(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {

			if(checkUtil.isNullByObject(params.get("proxyPrice"))){
				return R.error("请输入代理价");
			}
			if(!checkUtil.checkNumber( params.get("proxyPrice").toString())){
				return R.error("代理价应为数字");
			}
			BigDecimal proxyPrice = new BigDecimal(params.get("proxyPrice").toString());
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			String resMsg = "";
			int count = 0;
			for (int i=0;i<idList.size();i++){
				R res = tcwNeedPayLedgerDetailService.setProxyPrice(Long.parseLong(idList.get(i)),proxyPrice);
				if(res.getCode().equals( R.Code.FAILED.value)){
					resMsg += "批量设置的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
				}else {
					count++;
				}

			}
			return R.ok("成功操作"+count+"条数据</br>"+resMsg);
		} catch (IllegalArgumentException e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}




	/**
	 * 批量修改应付类型
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:setNeedPayType")
	@RequestMapping("/setNeedPayType")
	@ResponseBody
	public R setAdvanceType(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {

			if(checkUtil.isNullByObject(params.get("needPayTypeCode"))){
				return R.error("请选择应付类型");
			}

			String needPayTypeCode = params.get("needPayTypeCode").toString();
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			String resMsg = "";
			int count = 0;
			for (int i=0;i<idList.size();i++){
				R res = tcwNeedPayLedgerDetailService.setNeedPayType(Long.parseLong(idList.get(i)),needPayTypeCode);
				if(res.getCode().equals( R.Code.FAILED.value)){
					resMsg += "批量设置的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
				}else {
					count++;
				}

			}
			return R.ok("成功操作"+count+"条数据</br>"+resMsg);
		} catch (IllegalArgumentException e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}




	/**
	 * 批量设置已付金额
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:setPayedPrice")
	@RequestMapping("/setPayedPrice")
	@ResponseBody
	public R setPayedPrice(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {

			if(checkUtil.isNullByObject(params.get("payedPrice"))){
				return R.error("请输入已付金额");
			}
			if(!checkUtil.checkNumber( params.get("payedPrice").toString())){
				return R.error("已付金额应为数字");
			}
			BigDecimal payedPrice = new BigDecimal(params.get("payedPrice").toString());
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			String resMsg = "";
			int count = 0;
			for (int i=0;i<idList.size();i++){
				R res = tcwNeedPayLedgerDetailService.setPayedPrice(Long.parseLong(idList.get(i)),payedPrice);
				if(res.getCode().equals( R.Code.FAILED.value)){
					resMsg += "批量设置的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
				}else {
					count++;
				}

			}
			return R.ok("成功操作"+count+"条数据</br>"+resMsg);
		} catch (IllegalArgumentException e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}




	/**
	 * 批量修改交易类型
	 */
	@RequiresPermissions("tcwNeedPayLedgerDetail:setVjylx")
	@RequestMapping("/setVjylx")
	@ResponseBody
	public R setVjylx(HttpServletRequest request, @RequestParam Map<String, Object> params){
		try {

			if(checkUtil.isNullByObject(params.get("vjylx"))){
				return R.error("请选择交易类型");
			}

			String vjylx = params.get("vjylx").toString();
			String ids = params.get("ids").toString();
			String[] idArr = ids.split(",");
			List<String> idList = new ArrayList<>();
			Collections.addAll(idList,idArr);
			String resMsg = "";
			int count = 0;
			for (int i=0;i<idList.size();i++){
				R res = tcwNeedPayLedgerDetailService.setVjylx(Long.parseLong(idList.get(i)),vjylx);
				if(res.getCode().equals( R.Code.FAILED.value)){
					resMsg += "批量设置的第"+(i+1)+"条信息："+res.getMsg()+"</br>";
				}else {
					count++;
				}

			}
			return R.ok("成功操作"+count+"条数据</br>"+resMsg);
		} catch (IllegalArgumentException e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error(e.getMessage());
		} catch (Exception e) {
			logger.error("出错：",e.getMessage(),e);
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}



}
